package com.langll.ai.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.langll.ai.base.service.impl.BaseServiceImpl;
import com.langll.ai.stock.mapper.StockDailyDataMapper;
import com.langll.ai.stock.model.StockDailyData;
import com.langll.ai.stock.service.IStockDailyDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 股票日线数据 服务实现类
 * </p>
 *
 * @author langll
 * @since 2025-04-21
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class StockDailyDataServiceImpl extends BaseServiceImpl<StockDailyDataMapper, StockDailyData> implements IStockDailyDataService {

    private final StockDailyDataMapper stockDailyDataMapper;

    public StockDailyDataServiceImpl(StockDailyDataMapper stockDailyDataMapper) {
        super(stockDailyDataMapper);
        this.stockDailyDataMapper = stockDailyDataMapper;
    }

    @Override
    public List<StockDailyData> getStockDataByDateRange(String stockCode, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<StockDailyData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StockDailyData::getStockCode, stockCode)
                   .ge(StockDailyData::getTradeDate, startDate)
                   .le(StockDailyData::getTradeDate, endDate)
                   .orderByAsc(StockDailyData::getTradeDate);
        
        return stockDailyDataMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchSave(List<StockDailyData> stockDailyDataList) {
        int count = 0;
        for (StockDailyData stockDailyData : stockDailyDataList) {
            count += stockDailyDataMapper.insert(stockDailyData);
        }
        return count;
    }

    @Override
    public StockDailyData getLatestStockData(String stockCode) {
        QueryWrapper<StockDailyData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stock_code", stockCode)
                   .orderByDesc("trade_date")
                   .last("LIMIT 1");
        
        return stockDailyDataMapper.selectOne(queryWrapper);
    }
}